<?php

namespace LhpAmis\Traits;
use LhpAmis\Renderers\Amis;

trait ExportTrait
{
    /**
     * 导出按钮
     *
     * @param bool $disableSelectedItem
     *
     * @return \LhpAmis\Renderers\Service
     */
    protected function exportAction($disableSelectedItem = false, string $primaryKey = 'id')
    {
        // 获取主键名称
        // $primaryKey = $this->primaryKey();
        // 下载路径
        // $downloadPath = adminUrl('_download_export');
        $downloadPath = adminUrl('export');
        // 导出接口地址
        $exportPath = adminUrl('export');

        // 无数据提示
        $pageNoData = '无数据提示';
        // 选中行无数据提示
        $selectedNoData = '选中行无数据';
        // 按钮点击事件
        // $event = fn($script) => ['click' => ['actions' => [['actionType' => 'custom', 'script' => $script]]]];
        $event = function ($script) {
            return [
                'click' => [
                    'actions' => [
                        ['actionType' => 'custom', 'script' => $script]
                    ]
                ]
            ];
        };
        // 导出处理动作
        $doAction = "doAction([{actionType:'setValue',componentId:'export-action',args:{value:{showExportLoading:true}}},{actionType:'ajax',args:{api:{url:url.toString(),method:'get'}}},{actionType:'setValue',componentId:'export-action',args:{value:{showExportLoading:false}}},{actionType:'custom',expression:'\${event.data.responseResult.responseStatus===0}',script:'window.open(\'{$downloadPath}?path=\'+event.data.responseResult.responseData.path)'}])";
        // 按钮
        $buttons = [
            // 导出筛选
            Amis::make()->VanillaAction()->label('导出筛选')->onEvent(
                $event("let data=event.data;let params=Object.keys(data).filter(key=>key!=='page' && key!=='__super').reduce((obj,key)=>{obj[key]=data[key];return obj;},{});let url=new URL('{$exportPath}',window.location.origin);Object.keys(params).forEach(key=>url.searchParams.append(key,params[key]));{$doAction}")
            ),
            // // 导出全部
            // Amis::make()->VanillaAction()->label('导出全部')->onEvent(
            //     $event("let data=event.data;let params=Object.keys(data).filter(key=>key!=='page' && key!=='__super').reduce((obj,key)=>{obj[key]=data[key];return obj;},{});let url=new URL('{$exportPath}',window.location.origin);Object.keys(params).forEach(key=>url.searchParams.append(key,params[key]));{$doAction}")
            // ),
            // // 导出本页
            // Amis::make()->VanillaAction()->label('导出本页')->onEvent(
            //     $event("let ids=event.data.items.map(item=>item.{$primaryKey});if(ids.length===0){return doAction({actionType:'toast',args:{msgType:'warning',msg:'{$pageNoData}'}})};let url=new URL('{$exportPath}',window.location.origin);url.searchParams.append('id',ids.join(','));{$doAction}")
            // ),
        ];
        // // 导出选中项
        // if (!$disableSelectedItem) {
        //     $buttons[] = Amis::make()->VanillaAction()->label('导出选中项')->onEvent(
        //         $event("let ids=event.data.selectedItems.map(item=>item.{$primaryKey});if(ids.length===0){return doAction({actionType:'toast',args:{msgType:'warning',msg:'{$selectedNoData}'}})};let url=new URL('{$exportPath}',window.location.origin);url.searchParams.append('id',ids.join(','));{$doAction}")
        //     );
        // }

        $action = Amis::make()->Service()
            ->id('export-action')
            ->set('align', 'right')
            ->set('data', ['showExportLoading' => false])
            ->body(
                Amis::make()->Spinner()->set('showOn', '${showExportLoading}')->overlay()->body(
                    Amis::make()->DropdownButton()
                        ->label('导出')
                        ->set('icon', 'fa-solid fa-download')
                        ->buttons($buttons)
                        ->closeOnClick()
                        ->align('right')
                )
            );
        if (!$this->authAmis($action)) {
            return $action->disabled(true);
        }
        return $action;
    }
}
